package com.augurit.smartform.web.parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.smartform.constant.PageConstant;
import com.augurit.smartform.factory.ScriptEngineFactory;
import com.augurit.smartform.service.IFormExecuteService;
import com.augurit.smartform.service.ISmartFormService;
import com.augurit.smartform.service.IWfSupportService;
import com.augurit.smartform.test.TestService;
import com.augurit.smartform.util.JavaScriptJsonUtils;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.form.WfBusBaseEntity;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientExtAction;


@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.SUCCESS, location = "/smartform/success.jsp")
})
public class PageAction extends WfBusClientExtAction{
	
	@Autowired
	private TestService testService;
	
	@Autowired
	private ISmartFormService smartFormService;
	@Autowired
	private IFormExecuteService formExecuteService;
	@Autowired
	private IWfSupportService wfSupportService;
	
	private Page<Map> page=new Page<Map>(20);
	private Map pageMap=new HashMap();

	/**
	 * 根据PAGEID转到相关页面
	 */
	public void openPage(){
		HttpServletRequest request=this.getRequest();
		
//		String pageId=this.getParameter(PageConstant.KEY_PAGE_ID);
//		request.setAttribute(PageConstant.KEY_PAGE_ID, pageId);
		String pageCode=this.getParameter(PageConstant.KEY_PAGE_CODE);
		request.setAttribute(PageConstant.KEY_PAGE_CODE, pageCode);
		
		String id=this.getParameter(PageConstant.KEY_ID);
		request.setAttribute(PageConstant.KEY_ID, id);
		
		String pid=this.getParameter(PageConstant.KEY_MASTER_ENTITY_KEY);
		request.setAttribute(PageConstant.KEY_MASTER_ENTITY_KEY, pid);
		
		getRequest().setAttribute("CurrUserName",
				this.getLoginUser().getUser().getUserName());
		
		Map<String,Object> optionMap=formExecuteService.getOptionMap(request);
		pageMap.putAll(optionMap);
		
		Map<String,Object> defaultMap=formExecuteService.getDefaultMap(request);
		pageMap.putAll(defaultMap);														//将默认值放入页面MAP中
		
		this.executePageServer();														//执行页面部分后端JS代码
		
		if(super.getViewName() != null){
			super.initWfOpinions();															//初始化流程意见
		}
		
//		String path=smartFormService.getJspPath(pageId);
		String path=smartFormService.getJspPathByPageCode(pageCode);
		try {
			request.getRequestDispatcher(path).forward(request, this.getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 执行标签服务器端JS
	 */
	public void executeTagServer(){
		Map<String,Object>  map=new HashMap<String,Object>();
		HttpServletRequest request=this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine=ScriptEngineFactory.getBindingScriptEngine(map);
		formExecuteService.executeTagServer(scriptEngine, request);
	}
	
	/**
	 * 用AJAX方式执行标签服务器端JS
	 */
	public void ajaxExecuteTagServer(){
		Map<String,Object>  map=new HashMap<String,Object>();
		HttpServletRequest request=this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine=ScriptEngineFactory.getBindingScriptEngine(map);
		Object data=formExecuteService.executeTagServer(scriptEngine, request);
		if(data!=null){
			String jsonStr=this.javaScriptToStr(data);
//			System.out.println("+++++++++++++++++++++jsonStr="+jsonStr);
			this.renderJson(jsonStr);
		}
	}
	
	/**
	 * 保存业务并关联流程实例
	 */
	public String wfBusSave() throws Exception{
		this.executeWfSaveServer();									//保存之前执行后端JS函数
		
		Long id=null;
		WfBusInstanceTaskForm task = wfSupportService.wfBusSave(getRequest());
		WfBusBaseEntity form = new WfBusBaseEntity();
		if(task!=null&&task.getMasterEntityKey()!=null){
			id=Long.valueOf(task.getMasterEntityKey());
		}
		form.setId(id);
		WfUtils.renderWfBusSaveJson(task, form);
		return null;
	}
	
	/**
	 * 执行页面服务器端JS
	 */
	private void executePageServer(){
		Map<String,Object>  map=new HashMap<String,Object>();
		HttpServletRequest request=this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine=ScriptEngineFactory.getBindingScriptEngine(map);
		formExecuteService.executePageServer(scriptEngine, request);
	}
	
	/**
	 * 页面保存之前执行业务逻辑
	 */
	private void executeWfSaveServer(){
		Map<String,Object>  map=new HashMap<String,Object>();
		HttpServletRequest request=this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine=ScriptEngineFactory.getBindingScriptEngine(map);
		formExecuteService.executeWfSaveServer(scriptEngine, request);
	}
	
	/**
	 * 设置ENGINE的公共变量
	 * @param map
	 * cuigeqiang
	 */
	private void setEngineMap(Map map){
		map.put("request", this.getRequest());
		map.put("response", this.getResponse());
		map.put("service", formExecuteService);
		map.put("page", page);
		map.put("pageMap", pageMap);
		map.put("testService", testService);
	}
	
	/**
	 * 将后端JS对象转化成JAVA对象
	 * @param js
	 * @return
	 * cuigeqiang
	 */
	private String javaScriptToStr(Object js){
		if(js instanceof sun.org.mozilla.javascript.internal.NativeArray || js instanceof sun.org.mozilla.javascript.internal.NativeObject){
			String str="";
			try {
				str=JavaScriptJsonUtils.toJSONString(js);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return str;
		} if(js.getClass().getName().equals("sun.org.mozilla.javascript.internal.InterpretedFunction")){
			return "";
		}else{
			return Struts2Utils.getJsonString(js);
		}
	}

	public Page<Map> getPage() {
		return page;
	}

	public void setPage(Page<Map> page) {
		this.page = page;
	}
	
	public Map getPageMap() {
		return pageMap;
	}

	public void setPageMap(Map pageMap) {
		this.pageMap = pageMap;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public Object getModel() {
		// TODO Auto-generated method stub
		return null;
	}
}
